package simpleftp.server;

import java.net.ServerSocket;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Simple serveur TCP creant des thread pour gerer chaque connexion client.
 *
 * @author lom
 */
public class FTPServerMain
{

    /**
     * Port d'ecoute.
     */
    public static final int PORT = 7802;
    /**
     * Socket serveur d'accueil.
     */
    private static ServerSocket socketaccueil;
    private static double numberOfCores;
    private static int poolSize;
    private static ExecutorService executorPool;
    private static double blockingCoefficient = 0.9;

    public static void main(String argv[]) throws Exception
    {
        // TO BE COMPLETED - MAKE IT MULTITHREAD - 4  LINES (Completed)
        //Initialize an executorPool with the right poolsize
        numberOfCores = Runtime.getRuntime().availableProcessors();
        poolSize = (int) (numberOfCores / (1 - blockingCoefficient));
        executorPool = Executors.newFixedThreadPool(poolSize);

        try
        {
            socketaccueil = new ServerSocket(PORT);
            System.out.println("Server up and running.");
            FTPServer.setDebug(true);
            while (true)
            {
                FTPServer server = new FTPServer(socketaccueil.accept());
                //server.call(); // TO BE COMPLETED - 1 LINE (Completed)
                //When a client connect, dedicate a new instance of server to it in a new thread
                executorPool.submit(server);
            }
        } finally
        {
            if (socketaccueil != null)
            {
                socketaccueil.close();
            }
        }
    }
}
